package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.domain.User;
import com.itheima.result.R;
import com.itheima.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private UserService userService;


    /**
     * 发送短信验证码
     * @param user
     */
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody User user, HttpSession session){
        String msg = "1234";

        //把验证码保存到session中，因为后面在登录时还要用来验证
        session.setAttribute("msg",msg);
        log.info("1111");
        return R.success("验证码发送成功");
    }


    /**
     * 手机号，验证码登录
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R login(@RequestBody Map map,HttpSession session){

        //首先判断用户输入的验证码和我们生成的是否相同
        String phone = map.get("phone").toString();
        String code = map.get("code").toString();

        //从session中获取我们生成的验证码
        Object msg = session.getAttribute("msg");

        if(!code.equals(msg)){
            return R.error("验证码错误，请重新输入验证码");
        }

        //判断这个手机号是不是新用户，如果是新用户，就直接帮他注册
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getPhone,phone);
        User user = userService.getOne(lqw);

        if(user == null){
            //说明是新用户，直接帮他注册
            user = new User();
            user.setPhone(phone);
            user.setStatus(1);
            userService.save(user);
        }

        //在session中存一个标识，这样用户在访问其他页面时，能够正常放行访问
        session.setAttribute("user",user.getId());
        return R.success("登陆成功");
    }
}